﻿using System.Text;
using System.Xml;
using Domain;

namespace Infrastructure
{
    public class LogHtml : ILog
    {
        private const string LOG_FILE = "log.html";
        private XmlDocument logXMLFile;
        public LogHtml()
        {
            CreateDocument();
        }
        public string Log
        {
            get
            {
                var body = logXMLFile.GetElementsByTagName("body")[0];
                var log = new StringBuilder();
                if (body.HasChildNodes)
                {
                    foreach (XmlNode p in body.ChildNodes)
                    {
                        log.AppendLine(p.FirstChild.InnerText);
                    }
                }
                return log.ToString();
            }
            set
            {
                var body = logXMLFile.GetElementsByTagName("body")[0];
                var p = CreateElement("p", body);
                p.InnerText = value;
                SaveDocument();
            }
        }
        private void CreateDocument()
        {
            logXMLFile = new XmlDocument();
            var html = CreateElement("html", logXMLFile);
            var head = CreateElement("head", html);
            var body = CreateElement("body", html);
            var title = CreateElement("title", head);
            title.InnerText = "Log";
            SaveDocument();
        }
        private XmlElement CreateElement(string name, XmlNode parent)
        {
            return parent.AppendChild(logXMLFile.CreateElement(name)) as XmlElement;
        }
        private void SaveDocument()
        {
            logXMLFile.Save(LOG_FILE);
        }
    }
}
